package algotithm.leetcode.listnode.interview0202;

/**
 * @author zhouyanxiang
 * @Date 2021-02-2021/2/18-22:45
 * @URL https://leetcode-cn.com/problems/kth-node-from-end-of-list-lcci/
 * @Title 面试题 02.02. 返回倒数第 k 个节点
 */

import algotithm.leetcode.listnode.ListNode;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {

    public int kthToLast(ListNode head, int k) {
        ListNode first = head;
        ListNode second = head;
        //第一个指针先走k步
        while (k-- > 0) {
            first = first.next;
        }
        //然后两个指针在同时前进
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        return second.val;
    }

}
